package se.plingapp.backingbeans;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;
import se.plingapp.enterprisebeans.MessageFacade;
import se.plingapp.entitybeans.Message;
import se.plingapp.entitybeans.User;

/**
 * Message controller.
 *
 * @author Jens Björk
 */
@ManagedBean
@RequestScoped
public class MessageBean {

    @EJB
    private MessageFacade messageFacade;

    private Long messageId;

    private Message message = new Message();

    public Long getMessageId() {
        return this.messageId;
    }

    public void setMessageId(Long messageId) {
        this.messageId = messageId;
    }

    public Message getMessage() {
        return this.message;
    }

    public void setMessage(Message message) {
        this.message = message;
    }

    public void create() {
        User activeUser = this.getActiveUser();
        this.message.setUser(activeUser);
        this.messageFacade.create(this.message);
        this.message = new Message();
    }

    public String delete() {
        Message m = this.messageFacade.find(this.messageId);
        this.messageFacade.remove(m);
        return "dashboard.xhtml?faces-redirect=true";
    }

    public String like() {
        User activeUser = this.getActiveUser();
        Message m = this.messageFacade.find(this.messageId);
        m.addLike(activeUser);
        this.messageFacade.edit(m);
        return "dashboard.xhtml?faces-redirect=true";
    }

    public String unlike() {
        User activeUser = this.getActiveUser();
        Message m = this.messageFacade.find(this.messageId);
        m.removeLike(activeUser);
        this.messageFacade.edit(m);
        return "dashboard.xhtml?faces-redirect=true";
    }

    private User getActiveUser() {
        FacesContext fc = FacesContext.getCurrentInstance();
        return (User) fc.getExternalContext().getSessionMap().get("user");
    }
}
